package com.yunfeng.supercall.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.lin.activity.PersonalDetailCardActivity;
import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Parameters;
import com.ly.quickdev.library.adapter.ListBaseAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.ViewPhotoActivity;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.ChatMessageBean;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.manager.ChatMessageManager;
import com.yzx.api.UCSMessage;
import com.yzx.listenerInterface.RecordListener;

public class ChatMessageAdapter extends ListBaseAdapter<ChatMessageBean> {
	Context context;
	public static final int TYPE_ME_TO_OTHER_TEXT = 0;
	public static final int TYPE_ME_TO_OTHER_VOICE = 1;
	public static final int TYPE_ME_TO_OTHER_PIC = 2;
	public static final int TYPE_ME_TO_OTHER_MAP = 6;
	public static final int TYPE_OTHER_TO_ME_TEXT = 3;
	public static final int TYPE_OTHER_TO_ME_VOICE = 4;
	public static final int TYPE_OTHER_TO_ME_PIC = 5;
	public static final int TYPE_OTHER_TO_ME_MAP = 7;
	private UserBean mUser;
	private ContactsBaseBean mContactsBase;
	private ChatMessageManager mChatMessageManager;
	private ImageView mCurrentFullImage;
	private AnimationDrawable mCurrentDrawable;
	private ImageView mCurrentPlayingImgage;
	private SimpleDateFormat mSimpleDateFormat;
	private SensorManager mSensorManager;
	DisplayImageOptions options;
	public ChatMessageAdapter(Context context, List<ChatMessageBean> list) {
		super(context, list);
		this.context = context;
		mUser = BaseActivity.getUser(context);
		options = new DisplayImageOptions.Builder()
		.displayer(new RoundedBitmapDisplayer(context.getResources().getDimensionPixelOffset(R.dimen.corners_avatar)))
		.showImageOnFail(R.drawable.default_avatar)
		.showImageOnLoading(R.drawable.default_avatar)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
	}

	public ChatMessageAdapter(Context context, List<ChatMessageBean> list,
			ContactsBaseBean base) {
		this(context, list);
		this.context = context;
		mContactsBase = base;
		mChatMessageManager = ChatMessageManager.getInstance(context);
		mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		mSensorManager = (SensorManager) getContext().getSystemService(
				Context.SENSOR_SERVICE);
	}

	@Override
	public View initView(int position, View convertView, final ViewGroup parent) {
		// TODO Auto-generated method stub
		final int type = getItemViewType(position);
		final ChatMessageBean chatMessage = getItem(position);
		if (convertView == null) {
			switch (type) {
			case TYPE_ME_TO_OTHER_PIC:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_me_to_other_pic, null);
				break;
			case TYPE_ME_TO_OTHER_VOICE:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_me_to_other_voice, null);
				break;
			case TYPE_ME_TO_OTHER_TEXT:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_me_to_other_text, null);
				break;
			case TYPE_ME_TO_OTHER_MAP:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_me_to_other_map, null);
				break;
			case TYPE_OTHER_TO_ME_PIC:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_other_to_me_pic, null);
				break;
			case TYPE_OTHER_TO_ME_VOICE:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_other_to_me_voice, null);
				break;
			case TYPE_OTHER_TO_ME_TEXT:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_other_to_me_text, null);
				break;
			case TYPE_OTHER_TO_ME_MAP:
				convertView = getInflater().inflate(
						R.layout.list_item_chat_other_to_me_map, null);
				break;
			}
		}
		final ImageView avatar = ViewHolder.get(convertView, R.id.avatar);

		if (chatMessage.isSendFromMySelf()) {
			ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mUser.getPhoto(), avatar, options);
			avatar.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(context, PersonalDetailCardActivity.class);
					context.startActivity(intent);
				}
			});
		} else {
			ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mContactsBase.getPhoto(), avatar, options);
			avatar.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(context, PersonalDetailCardActivity.class);
					intent.putExtra("data", mContactsBase);
					context.startActivity(intent);
				}
			});
		}
		showTimeIfNeed(chatMessage, position, convertView);
		final ImageView iv = ViewHolder.get(convertView, R.id.iv);
		switch (type) {
		case TYPE_ME_TO_OTHER_PIC:
			AppContext.displayLocalImg(iv, chatMessage.getContent());
			iv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					List<String> list = new ArrayList<String>();
					list.add(chatMessage.getContent());
					startActivity(new Intent(getContext(),
							ViewPhotoActivity.class).putStringArrayListExtra(
									Constants.KEY_DATA, (ArrayList<String>) list)
									.putExtra(Constants.KEY_PASS, true));
				}
			});
			iv.setOnLongClickListener(new LongClick(chatMessage, position));
			break;
		case TYPE_OTHER_TO_ME_PIC:
			AppContext.displayLocalImg(iv, chatMessage.getContent());
			iv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					List<String> list = new ArrayList<String>();
					list.add(chatMessage.getContent());
					startActivity(new Intent(getContext(),
							ViewPhotoActivity.class).putStringArrayListExtra(
									Constants.KEY_DATA, (ArrayList<String>) list)
									.putExtra(Constants.KEY_PASS, false));
				}
			});
			iv.setOnLongClickListener(new LongClick(chatMessage, position));
			break;
		case TYPE_OTHER_TO_ME_VOICE:
		case TYPE_ME_TO_OTHER_VOICE:
//			chatMessage.setHasRead(false);
			handleVoiceView(convertView, chatMessage, position);
			break;
		case TYPE_OTHER_TO_ME_MAP:
		case TYPE_ME_TO_OTHER_MAP:
			MapView mapView = ViewHolder.get(convertView, R.id.bmapView);
			mapView.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					if (event.getAction() == MotionEvent.ACTION_UP) {
						parent.requestDisallowInterceptTouchEvent(false);
					} else {
						parent.requestDisallowInterceptTouchEvent(true);
					}
					return false;
				}
			});
			ViewHolder.get(convertView, R.id.indicator_area)
			.setOnLongClickListener(
					new LongClick(chatMessage, position));
			handleMapView(mapView, chatMessage.getContent(), convertView);
			break;
		default:
			TextView content = ViewHolder.get(convertView, R.id.chat_content);
			content.setText(chatMessage.getContent());
			content.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					showTextDialog(chatMessage.getContent(), chatMessage);
					return true;
				}
			});
			break;
		}

		return convertView;
	}

	private void showTextDialog(final String content,
			final ChatMessageBean chatMessage) {
		Builder mBuilder = new Builder(getContext());
		mBuilder.setTitle(R.string.choose_operation);
		mBuilder.setItems(R.array.long_press_menus,
				new Dialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					ClipboardManager mClipboardManager = (ClipboardManager) getContext()
					.getSystemService(Context.CLIPBOARD_SERVICE);
					ClipData mClipData = ClipData.newPlainText(content,
							content);
					mClipboardManager.setPrimaryClip(mClipData);
					Toast.makeText(getContext(), R.string.copy_success,
							Toast.LENGTH_SHORT).show();
					break;
				case 1:
					mChatMessageManager.deleteMessages(chatMessage,
							mContactsBase);
					notifyDataSetChanged();
					break;
				}
			}
		});
		mBuilder.setNegativeButton(android.R.string.cancel, null);
		mBuilder.show();

	}

	private void showTimeIfNeed(ChatMessageBean content, int position, View view) {
		TextView time = ViewHolder.get(view, R.id.chat_time);
		if (time == null) {
			return;
		}
		if (position == 0) {
			long now = content.getReceiveTime();
			time.setText(mSimpleDateFormat.format(new Date(now)));
			time.setVisibility(View.VISIBLE);
		}
		if (position > 0) {
			ChatMessageBean previous = getList().get(position - 1);
			long rec = previous.getReceiveTime();
			long now = content.getReceiveTime();
			if (now - rec > 60 * 1000 * 3) {
				time.setText(mSimpleDateFormat.format(new Date(now)));
				time.setVisibility(View.VISIBLE);
			} else {
				time.setVisibility(View.GONE);
			}
		}

	}

	private void handleMapView(MapView mapView, String content, View view) {
		try {
			JSONObject json = new JSONObject(content);
			json = new JSONObject(json.getString("location"));
			BaiduMap baiduMap = mapView.getMap();
			//			String text = json.getString("description");
			//			TextView tv = ViewHolder.get(view, R.id.content);
			//			tv.setText(getContext().getString(R.string.at_somewhere, text));
			double lat = Double.valueOf(json.getString("latitude"));
			double lng = Double.valueOf(json.getString("longitude"));
			MapStatusUpdate factory = MapStatusUpdateFactory
					.newLatLng(new LatLng(lat, lng));
			MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory
					.zoomTo(14f);
			baiduMap.animateMapStatus(factory);
			baiduMap.animateMapStatus(mapStatusUpdate);
			// 定义Maker坐标点
			LatLng point = new LatLng(lat, lng);
			// 构建Marker图标
			BitmapDescriptor bitmap = BitmapDescriptorFactory
					.fromResource(R.drawable.ic_location);
			// 构建MarkerOption，用于在地图上添加Marker
			OverlayOptions option = new MarkerOptions().position(point).icon(
					bitmap);
			// 在地图上添加Marker，并显示
			baiduMap.addOverlay(option);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void releaseSensors() {
		mSensorManager.unregisterListener((SensorEventListener) getContext(),
				mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY));
	}

	/**
	 * 处理语音相关的view
	 * 
	 * @param convertView
	 * @param chatMessage
	 * @param position
	 */
	public void handleVoiceView(View convertView,
			final ChatMessageBean chatMessage, int position) {
		final ImageView iv = ViewHolder.get(convertView, R.id.iv);
		final View clickArea = ViewHolder.get(convertView, R.id.indicator_area);
		final ImageView hasRead = ViewHolder.get(convertView, R.id.hasRead);
		final ImageView full = ViewHolder.get(convertView, R.id.iv_full);
		hasRead.setVisibility(chatMessage.isHasRead() ? View.GONE
				: View.VISIBLE);
		final TextView lenth = ViewHolder.get(convertView, R.id.voice_lenth);
		lenth.setText(chatMessage.getVoiceLenth() + "\"");
		final AnimationDrawable animationDrawable = (AnimationDrawable) iv
				.getDrawable();
		clickArea.setOnLongClickListener(new LongClick(chatMessage, position));
		animationDrawable.stop();
		clickArea.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!chatMessage.isHasRead()) {
					chatMessage.setHasRead(true);
					mChatMessageManager.updateMessages(chatMessage);
					hasRead.setVisibility(View.GONE);
					
					DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(context, "db", 2);
					mDatabaseHelperForChattingMap.resetZeroUCSMessage(chatMessage.getId() + "");
					if(mDatabaseHelperForChattingMap != null) {
					mDatabaseHelperForChattingMap.close();
					mDatabaseHelperForChattingMap = null;
					}
					
				}
				if (mCurrentDrawable != null) {
					mCurrentDrawable.stop();
				}
				if (mCurrentFullImage != null) {
					mCurrentFullImage.setVisibility(View.VISIBLE);
				}
				if (mCurrentPlayingImgage != null) {
					mCurrentPlayingImgage.setVisibility(View.GONE);
				}
				if (UCSMessage.isPlaying()) {
					UCSMessage.stopPlayerVoice();
					return;
				}
				animationDrawable.start();
				mCurrentDrawable = animationDrawable;
				mCurrentPlayingImgage = iv;
				mCurrentFullImage = full;
				iv.setVisibility(View.VISIBLE);
				full.setVisibility(View.GONE);
				mSensorManager.registerListener(
						(SensorEventListener) getContext(),
						mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
						SensorManager.SENSOR_DELAY_NORMAL);
				UCSMessage.startPlayerVoice(chatMessage.getContent(),
						new RecordListener() {

					@Override
					public void onFinishedRecordingVoice(int arg0) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onFinishedPlayingVoice() {
						// TODO Auto-generated method stub
						animationDrawable.stop();
						iv.setVisibility(View.GONE);
						full.setVisibility(View.VISIBLE);
						mSensorManager
						.unregisterListener((SensorEventListener) getContext());
					}
				});
			}
		});
	}

	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
		final ChatMessageBean message = getItem(position);
		if (message.isSendFromMySelf()) {
			switch (message.getChatType()) {
			case ChatMessageBean.TYPE_PIC:

				return TYPE_ME_TO_OTHER_PIC;
			case ChatMessageBean.TYPE_TEXT:

				return TYPE_ME_TO_OTHER_TEXT;
			case ChatMessageBean.TYPE_VOICE:

				return TYPE_ME_TO_OTHER_VOICE;
			case ChatMessageBean.TYPE_LOCATION:
				return TYPE_ME_TO_OTHER_MAP;
			}
		} else {
			switch (message.getChatType()) {
			case ChatMessageBean.TYPE_PIC:
				return TYPE_OTHER_TO_ME_PIC;
			case ChatMessageBean.TYPE_TEXT:
				return TYPE_OTHER_TO_ME_TEXT;
			case ChatMessageBean.TYPE_VOICE:
				return TYPE_OTHER_TO_ME_VOICE;
			case ChatMessageBean.TYPE_LOCATION:
				return TYPE_OTHER_TO_ME_MAP;
			}
		}
		return TYPE_OTHER_TO_ME_PIC;
	}

	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 8;
	}

	public class LongClick implements OnLongClickListener {

		private ChatMessageBean mChatMessage;
		private int mPosition;

		LongClick(ChatMessageBean chatMessage, int position) {
			mChatMessage = chatMessage;
			mPosition = position;
		}

		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			Builder mBuilder = new Builder(getContext());
			mBuilder.setTitle(R.string.choose_operation);
			mBuilder.setItems(R.array.long_press_menus_single,
					new Dialog.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					mChatMessageManager.deleteMessages(mChatMessage,
							mContactsBase);
					notifyDataSetChanged();
				}
			});
			mBuilder.setNegativeButton(android.R.string.cancel, null);
			mBuilder.show();
			return true;
		}

	}

}
